package com.example.util;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.dingtalk.api.DefaultDingTalkClient;
import com.dingtalk.api.DingTalkClient;
import com.dingtalk.api.request.*;
import com.dingtalk.api.response.*;
import com.example.domain.User;
import com.example.service.UserService;
import com.example.service.serviceImpl.UserServiceImpl;
import com.taobao.api.ApiException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

@Controller
public class DTalkConnect {

    @Autowired
    UserService userService=new UserServiceImpl();

    public String GetToken(HttpServletRequest request) {
        try {
            DingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/gettoken");
            OapiGettokenRequest req = new OapiGettokenRequest();
            req.setAppkey("ding1wiwmulky5fc6uva");
            req.setAppsecret("2QSQGYNP5b7Hivzv0cAwY_WhSTo6Wpj02vCvCrzwlCsH-1tRAuOpaRtcR_xgx1Gn");
            req.setHttpMethod("GET");
            OapiGettokenResponse rsp = null;
            rsp = client.execute(req);
            JSONObject object = JSONObject.parseObject(rsp.getBody());
            String token = object.getString("access_token");
            HttpSession session = request.getSession();
            session.setAttribute("Token",token);
            System.out.println("TOKEN:"+token);
            return rsp.getAccessToken();
        } catch (ApiException e) {
            return "获取TOKEN出错！";
        }
    }

    @ResponseBody
    @RequestMapping(value = "/SendCode")
    public ModelAndView JobId_Get(@RequestParam("code") String code,
                                  @RequestParam("phone") String phone,
                                  HttpServletRequest request){
        String token=GetToken(request);
        String uid;
        String adminLevel = null;
        User user = new User();

        //获取钉钉里面的uid
        try {
            DingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/topapi/v2/user/getuserinfo");
            OapiV2UserGetuserinfoRequest req = new OapiV2UserGetuserinfoRequest();
            req.setCode(code);
            OapiV2UserGetuserinfoResponse rsp = client.execute(req, token);

            JSONObject object = JSONObject.parseObject(rsp.getBody());
            //uid.getJSONObject("result").getString("userid");
            uid = object.getJSONObject("result").getString("userid");
        } catch (ApiException e) {
            e.printStackTrace();
            return new ModelAndView("error.html");
        }
        //登录尝试
        try {
            DingTalkClient cli = new DefaultDingTalkClient("https://oapi.dingtalk.com/topapi/v2/user/get");
            OapiV2UserGetRequest req = new OapiV2UserGetRequest();
            req.setUserid(uid);
            req.setLanguage("zh_CN");
            OapiV2UserGetResponse rsp = cli.execute(req, token);
            JSONObject object = JSONObject.parseObject(rsp.getBody());
            String jobid=object.getJSONObject("result").getString("job_number");
            System.out.println(rsp.getBody()+"\t工号："+jobid);
            int id = Integer.parseInt(jobid);

            //判断是否是超级管理员
            try {

                DingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/topapi/user/listadmin");
                OapiUserListadminRequest adminreq = new OapiUserListadminRequest();
                OapiUserListadminResponse adminrsp = client.execute(adminreq, token);
                JSONObject jsonObject = JSONObject.parseObject(adminrsp.getBody());
                JSONArray jsonArray = jsonObject.getJSONArray("result");
                //获取所有的管理员列表，和uid一个个作比对，相同的就返回权限。
                for (int i=0;i<jsonArray.size();i++){
                    JSONObject jo = jsonArray.getJSONObject(i);
                    if (uid.equals(jo.getString("userid"))) {
                        System.out.println(jo.toString());      //超管的时候输出
                        adminLevel=jo.getString("sys_level");break;
                    }
                }

                //判断：当是超管的时候进入main页面
                if(!adminLevel.equals("1")) {
                    user = userService.selectLimitById(id);
                    System.out.println(user.getLimit());
                }else if(adminLevel.equals("1")){
                    return new ModelAndView("/manager/main.html");
                }
            } catch (ApiException e) {
                e.printStackTrace();
                return new ModelAndView("/error.html");
            }

            //存储工号
            HttpSession session = request.getSession();
            session.setAttribute("id",id);

            //当数据库里面是管理员的时候，去管理页面。否则直接去盘点页面。
            if (user.getLimit().equals("管理员")){
                if (phone.equals("1")){
                    return new ModelAndView("/manager/phonePage.html");
                }else {
                    return new ModelAndView("/manager/main.html");
                }
            }else{
                if (phone.equals("1")) {
                    return new ModelAndView("/user/check.html");
                }else{
                    return new ModelAndView("/user/ComputerPage.html");
                }
            }

        } catch (ApiException e) {
            e.printStackTrace();
            return new ModelAndView("/error.html");
        }
    }

}
